<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\token\driver\Redis;
use think\Db;
use think\Request;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 首页接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }


    /*
    * 发送验证码(type:1注册，0登录)
    */
    public function send_code()
    {
        $m_code = Db::name('code');
        $m_userhome = Db::name('userhome');
        $request = Request::instance();

        $phone = $request->param("phone");
        $type = $request->param("type") ? $request->param("type") : 0;

        $map['phone'] = $phone;
        $u_data = $m_userhome->where($map)->find();
        /*
                if(!empty($u_data) and !empty($type)){
                    $this->error('手机号已存在','','201');
                }
                if(empty($u_data) and empty($type)){
                    $this->error('该用户未注册','','201');
                }
                */
        if ($type == 1) {
            $res = DB::name('userhome')->where('phone', $phone)->find();
//            if ($res) {
//                $this->error('该手机号已被注册', '', '201');
//            }
        }

        $str = '11223344556677889900';
        $randStr = str_shuffle($str);//打乱字符串
        $rands = substr($randStr, 0, 6);//substr(string,start,length);返回字符串的一部分

        $result = $this->app_short_message($phone, $rands);
        #dump($result);die;

        $data['name'] = $phone;
        $data['code'] = $rands;
        $data['create_time'] = time();
        $data['status'] = 1;
        $data = $m_code->insertGetId($data);
//        $redis = new Redis();
//        $redis->set($rands,$phone,900);
        if (!empty($data)) {
            $this->success('请求成功', $rands, '200');
        }
    }

    //注销账号
    public function zhuxiao()
    {
        $request = Request::instance();

        $phone = $request->param("phone");
        $uid = $request->param("uid");

        $res = yanzheng($uid, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        DB::name('userhome')->where('id', $uid)->where('phone', $phone)->update(['is_zhuxiao_switch' => 1]);//1=注销账号,0=正常
        $this->success('ok', '', 200);
    }


    /*
    * 验证验证码
    */
    public function if_code()
    {
        $m_code = Db::name('code');
        $request = Request::instance();

        $name = $request->param("phone");
        $code = $request->param("code");

        if (empty($name)) {
            $this->error("手机号不能未空");
        }

        if (empty($code)) {
            $this->error("验证码不能为空");
        }

        $map['name'] = $name;
        $map['code'] = $code;
        $map['create_time'] = array('egt', time() - 300);
        $map['status'] = 1;
        $data = $m_code->where($map)->find();
        if (!empty($data)) {
            $s_map['id'] = $data['id'];
            $s_data['status'] = 0;
            $result = $m_code->where($s_map)->delete();

        } else {
            $this->error("验证码错误", '', '201');
        }
    }

    public function add_openid()
    {
        $m_userhome = Db::name("userhome");
        $request = Request::instance();
        $code = $request->param("code");
        $encryptedData = $request->param("encryptedData");
        $iv = $request->param("iv");

        $appid = 'wx4a40935421da4a92';
        $secret = 'f2c422ad0b14d3a37b0170100519fba5';

        $weixin = file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code");

        #通过code换取access_token
        $jsondecode = json_decode($weixin);
        $array = get_object_vars($jsondecode);
        #dump($array);die;
        if (!empty($array['errcode'])) {
            $this->error("请重新授权");
        }
        #获取手机号
        $array['phone'] = $this->phone_add($array['session_key'], $encryptedData, $iv);

        $this->success("成功", $array);
    }


    public function phone_add($sessionKey, $encryptedData, $iv)
    {
        include_once "./api/wxsq/wxBizDataCrypt.php";

        $request = Request::instance();

        $appid = 'wx4a40935421da4a92';
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        if ($errCode == 0) {
            return $data;
        } else {
            $this->error("出现错误", $errCode);
        }

    }

    /*
    * 登录
    */
    public function login()
    {
        $m_userhome = Db::name("userhome");

        $request = Request::instance();
        $phone = $request->param("phone");
        $password = $request->param("pwd");
        $xcxopenid = $request->param("xcxopenid") ?: '';//小程序openid 非必填
        $map['phone'] = $phone;
        $data = $m_userhome->field("id,password,avatar,nickname,token,phone,is_suosi_switch,is_renzheng,is_zhuxiao_switch,inviteCode,isVip,vipTime")->where($map)->find();
        if (empty($data)) {
            $this->error("账号不存在");
        }

        if (md5($password) != $data['password']) {
            $this->error("密码错误");
        }

        if ($data['is_suosi_switch'] == 1) {
            $this->error("账号已禁用");
        }

        if ($data['is_zhuxiao_switch'] == 1) {
            $this->error("您的账号已注销，暂时无法登录，请联系客服处理，联系电话0755-2690489");
        }
        if (!$data['inviteCode']) {
            #创建邀请码
            $newInviteCode = date('YmdHis') . rand(0, 9) . rand(0, 9);
            $yq_image = $this->create_image($newInviteCode);
            $yq_map['id'] = $data['id'];
            $yq_data['inviteCode'] = $newInviteCode;
            $yq_data['invite_image'] = $yq_image;
            $m_userhome->where($yq_map)->update($yq_data);
            $data['inviteCode'] = $newInviteCode;
            $data['invite_image'] = $yq_image;
        }

        #修改token
        $s_map['id'] = $data['id'];
        $s_data['token'] = md5(time() . rand(100, 999));
        if ($xcxopenid) {
            $s_data['xcxopenid'] = $xcxopenid;
            $data['xcxopenid'] = $xcxopenid;
            $user_xcxopenid = DB::name('userhome')->where('phone', $phone)->value('xcxopenid');
            if ($user_xcxopenid && $user_xcxopenid != $xcxopenid) {
                $this->error('该手机号已经绑定过其它微信');
            }
            // $chaxun_xcxopenid =  DB::name('userhome')->where('xcxopenid',$xcxopenid)->value('xcxopenid');
            // if ($chaxun_xcxopenid) {
            //     $this->error('该微信已经绑定过其它手机号');
            // }
        }
        $m_userhome->where($s_map)->update($s_data);

        $data['avatar'] = $this->image_url($data['avatar']);
        $data['token'] = $s_data['token'];
        $status = Db::name("userstore")->where("userhome_id = {$data['id']}")->value("status");
        if (!$status) {
            $status = 0;
        }
        $data['status'] = $status;
        // unset($data['phone']);
        unset($data['password']);

        $this->success("成功", $data, '200');
    }

    /*
    * 三方 登录
    */
    public function tripartite_login()
    {
        $m_userhome = Db::name("userhome");

        $request = Request::instance();
        $openid = $request->param("openid");
        $wxopenid = $request->param("wxopenid");
        $password = $request->param("pwd");
        $type = $request->param("type") ? $request->param("type") : 1;   #1=微信,2=qq,3=支付宝

        if ($type == 1) {
            if(empty($wxopenid) || empty($openid)){
                $this->error("参数缺少");
            }
            $map['wxopenid'] = $wxopenid;
        } elseif ($type == 2) {
            $map['qqopenid'] = $openid;
        } elseif ($type == 3) {
            $map['zfbopenid'] = $openid;
        } else {
            if(empty($wxopenid) || empty($openid)){
                $this->error("参数缺少");
            }
            $map['wxopenid'] = $wxopenid;
            //$map['xcxopenid'] = $openid;
        }

        $data = $m_userhome->field("id,avatar,nickname,token,is_suosi_switch,is_renzheng,phone,is_zhuxiao_switch,inviteCode")->where($map)->find();
        if (empty($data)) {
            if ($type == 4) {
                $data = $m_userhome->field("id,avatar,nickname,token,is_suosi_switch,is_renzheng,phone,is_zhuxiao_switch,inviteCode")->where('xcxopenid', $openid)->find();
                if (empty($data)) {
                    $this->error("账号不存在");
                }
                $m_userhome->where('id', $data['id'])->update(['wxopenid' => $wxopenid]);
            } else if ($type == 1) {
                $data = $m_userhome->field("id,avatar,nickname,token,is_suosi_switch,is_renzheng,phone,is_zhuxiao_switch,inviteCode")->where('wxopenid', $openid)->find();
                if (empty($data)) {
                    $this->error("账号不存在");
                }
                $m_userhome->where('id', $data['id'])->update(['wxopenid' => $wxopenid]);
            } else {
                if (empty($data)) {
                    $this->error("账号不存在");
                }
            }
        }
        if ($type == 4) {
            if (!isset($data['appletOpenid']) || empty($data['appletOpenid'])) {
                $m_userhome->where('id', $data['id'])->update(['appletOpenid' => $openid]);
            }
        } else if ($type == 1) {
            if (!isset($data['appOpenid']) || empty($data['appOpenid'])) {
                $m_userhome->where('id', $data['id'])->update(['appOpenid' => $openid]);
            }
        }
        if ($data['is_suosi_switch'] == 1) {
            $this->error("账号已禁用");
        }
        if ($data['is_zhuxiao_switch'] == 1) {
            $this->error("您的账号已注销，暂时无法登录，请联系客服处理，联系电话0755-2690489", '', 202);
        }
        if (!$data['inviteCode']) {
            #创建邀请码
            $newInviteCode = date('YmdHis') . rand(0, 9) . rand(0, 9);
            $yq_image = $this->create_image($newInviteCode);
            $yq_map['id'] = $data['id'];
            $yq_data['inviteCode'] = $newInviteCode;
            $yq_data['invite_image'] = $yq_image;
            $m_userhome->where($yq_map)->update($yq_data);
            $data['inviteCode'] = $newInviteCode;
            $data['invite_image'] = $yq_image;
        }
        #修改token
        $s_map['id'] = $data['id'];
        $s_data['token'] = md5(time() . rand(100, 999));
        // $s_data['password'] = md5($password);
        $m_userhome->where($s_map)->update($s_data);

        $data['avatar'] = $this->image_url($data['avatar']);
        $data['token'] = $s_data['token'];
        $status = Db::name("userstore")->where("userhome_id = {$data['id']}")->value("status");
        if (!$status) {
            $status = 0;
        }
        $data['status'] = $status;

        $this->success("成功", $data, '200');
    }

    /*
    * 短信 登录
    */
    public function sms_login()
    {
        $m_userhome = Db::name("userhome");

        $request = Request::instance();
        $phone = $request->param("phone");
        $xcxopenid = $request->param("xcxopenid") ?: '';//小程序openid 非必填


        $map['phone'] = $phone;
        $data = $m_userhome->field("id,avatar,nickname,token,is_suosi_switch,phone,is_zhuxiao_switch,inviteCode")->where($map)->find();
        if (empty($data)) {
            $this->error("账号不存在");
        }
        if ($data['is_suosi_switch'] == 1) {
            $this->error("账号已禁用");
        }
        if ($data['is_zhuxiao_switch'] == 1) {
            $this->error("您的账号已注销，暂时无法登录，请联系客服处理，联系电话0755-2690489");
        }
        $this->if_code();

        if (!$data['inviteCode']) {
            #创建邀请码
            $newInviteCode = date('YmdHis') . rand(0, 9) . rand(0, 9);
            $yq_image = $this->create_image($newInviteCode);
            $yq_map['id'] = $data['id'];
            $yq_data['inviteCode'] = $newInviteCode;
            $yq_data['invite_image'] = $yq_image;
            $m_userhome->where($yq_map)->update($yq_data);
            $data['inviteCode'] = $newInviteCode;
            $data['invite_image'] = $yq_image;
        }
        #修改token
        $s_map['id'] = $data['id'];
        $s_data['token'] = md5(time() . rand(100, 999));
        if ($xcxopenid) {
            $s_data['xcxopenid'] = $xcxopenid;
            $data['xcxopenid'] = $xcxopenid;
            $user_xcxopenid = DB::name('userhome')->where('phone', $phone)->value('xcxopenid');
            if ($user_xcxopenid && $user_xcxopenid != $xcxopenid) {
                $this->error('该手机号已经绑定过其它微信');
            }
            $chaxun_xcxopenid = DB::name('userhome')->where('xcxopenid', $xcxopenid)->value('xcxopenid');
            if ($chaxun_xcxopenid) {
                $this->error('该微信已经绑定过其它手机号');
            }
        }
        $m_userhome->where($s_map)->update($s_data);

        $data['avatar'] = $this->image_url($data['avatar']);
        $data['token'] = $s_data['token'];
        $status = Db::name("userstore")->where("userhome_id = {$data['id']}")->value("status");
        if (!$status) {
            $status = 0;
        }
        $data['status'] = $status;
        $this->success("成功", $data, '200');
    }

    public function getBinding()
    {
        $request = Request::instance();
        $phone = $request->param("phone");//用户id
        if(isset($phone)){
            $user = Db::name("userhome")->where('phone', $phone)->field('wxopenid,qqopenid,zfbopenid')->find();
            $data = [];
            $data['isWX'] = 0;
            $data['isQQ'] = 0;
            $data['isZFB'] = 0;
            if(!empty($user)){
                if (!empty($user['wxopenid'])) {
                    $data['isWX'] = 1;
                }
                if (!empty($user['qqopenid'])) {
                    $data['isQQ'] = 1;
                }
                if (!empty($user['zfbopenid'])) {
                    $data['isZFB'] = 1;
                }
                $this->success("检验通过", $data, '200');
            }else{
                $this->success("检验通过", $data, '200');
            }
        }
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $user = Db::name("userhome")->where('id', $userhome_id)->field('wxopenid,qqopenid,zfbopenid')->find();
        $data = [];
        $data['isWX'] = 0;
        $data['isQQ'] = 0;
        $data['isZFB'] = 0;
        if (!empty($user['wxopenid'])) {
            $data['isWX'] = 1;
        }
        if (!empty($user['qqopenid'])) {
            $data['isQQ'] = 1;
        }
        if (!empty($user['zfbopenid'])) {
            $data['isZFB'] = 1;
        }
        $this->success("成功", $data, '200');
    }

    public function binding()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $bangdingType = $request->param("bangdingType") ? $request->param("bangdingType") : null;
        $openid = $request->param("openid") ? $request->param("openid") : null;
        $unionid = $request->param("unionid") ? $request->param("unionid") : null;
        if (empty($bangdingType) || empty($openid)) {
            $this->error('参数不完整');
        }
        if ($bangdingType == "XCX" || $bangdingType == "PCWX" || $bangdingType == "APPWX") {
            if (empty($unionid)) {
                $this->error('微信登录缺乏unionid');
            }
        }
        $data = [];
        $sql = Db::name("userhome");
        if ($bangdingType == "XCX") {
            $data['wxopenid'] = $unionid;
            $data['appletOpenid'] = $openid;
            $data['pcOpenid'] = null;
            $data['appOpenid'] = null;
            $sql->where('wxopenid', $unionid);
        }
        if ($bangdingType == "PCWX") {
            $data['wxopenid'] = $unionid;
            $data['pcOpenid'] = $openid;
            $data['appletOpenid'] = null;
            $data['appOpenid'] = null;
            $sql->where('wxopenid', $unionid);
        }
        if ($bangdingType == "APPWX") {
            $data['wxopenid'] = $unionid;
            $data['appOpenid'] = $openid;
            $data['pcOpenid'] = null;
            $data['appletOpenid'] = null;
            $sql->where('wxopenid', $unionid);
        }
        if ($bangdingType == "QQ") {
            $data['qqopenid'] = $openid;
            $sql->where('qqopenid', $openid);
        }
        if ($bangdingType == "ZFB") {
            $data['zfbopenid'] = $openid;
            $sql->where('zfbopenid', $openid);
        }
        $num = $sql->count();
        if ($num) {
            $this->success('该账号已被人绑定', '', '220');
        }
        Db::name("userhome")->where('id', $userhome_id)->update($data);
        $this->success('绑定成功', '', '200');
    }

    public function relieveBinding()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $bangdingType = $request->param("bangdingType") ? $request->param("bangdingType") : null;
        if (empty($bangdingType)) {
            $this->error('参数不完整');
        }
        $data = [];
        if ($bangdingType == "WX") {
            $data['wxopenid'] = null;
            $data['appletOpenid'] = null;
            $data['pcOpenid'] = null;
            $data['appOpenid'] = null;
        }
        if ($bangdingType == "XCX") {
            $data['wxopenid'] = null;
            $data['appletOpenid'] = null;
            $data['pcOpenid'] = null;
            $data['appOpenid'] = null;
        }
        if ($bangdingType == "PCWX") {
            $data['wxopenid'] = null;
            $data['appletOpenid'] = null;
            $data['pcOpenid'] = null;
            $data['appOpenid'] = null;
        }
        if ($bangdingType == "APPWX") {
            $data['wxopenid'] = null;
            $data['appletOpenid'] = null;
            $data['pcOpenid'] = null;
            $data['appOpenid'] = null;
        }
        if ($bangdingType == "QQ") {
            $data['qqopenid'] = null;
        }
        if ($bangdingType == "ZFB") {
            $data['zfbopenid'] = null;
        }
        Db::name("userhome")->where('id', $userhome_id)->update($data);
        $this->success('解绑成功', '', '200');
    }


    /*
    * 注册
    */
    public function register()
    {
        $m_userhome = Db::name("userhome");
        $m_userphone = Db::name("userphone");
        $m_usergroup = Db::name("usergroup");
        $m_userrelation = Db::name("user_relation");
        $m_user_invite_num = Db::name("user_invite_num");

        $request = Request::instance();
        $nickname = $request->param("nickname");
        $avatar = $request->param("avatar");
        $phone = $request->param("phone");
        $pwd = $request->param("pwd");
        $code = $request->param("code");
        $wxopenid = $request->param("wxopenid") ? $request->param("wxopenid") : '';
        $qqopenid = $request->param("qqopenid") ? $request->param("qqopenid") : '';
        $zfbopenid = $request->param("zfbopenid") ? $request->param("zfbopenid") : '';
        $xcxopenid = $request->param("xcxopenid") ? $request->param("xcxopenid") : '';
        $inviteCode = $request->param("inviteCode") ? $request->param("inviteCode") : null;

        #判断是否注册
        $map['phone'] = $phone;
        $data = $m_userhome->where($map)->find();
        if ((isset($wxopenid) && !empty($wxopenid)) || (isset($qqopenid) && !empty($qqopenid)) || (isset($zfbopenid) && !empty($zfbopenid)) || (isset($xcxopenid) && !empty($xcxopenid))) {
            $userThree = Db::name("userhome");
            if (!empty($wxopenid)) {
                $userThree->where('wxopenid', $wxopenid);
            }
            if (!empty($qqopenid)) {
                $userThree->where('qqopenid', $qqopenid);
            }
            if (!empty($zfbopenid)) {
                $userThree->where('zfbopenid', $zfbopenid);
            }
            if (!empty($xcxopenid)) {
                $userThree->where('xcxopenid', $xcxopenid);
            }
            $user = $userThree->find();
            if ($user) {
                $this->error("该第三方信息已被绑定");
            }
        }
        if (!empty($data)) {
            if (!empty($wxopenid)) {
                $update_data['wxopenid'] = $wxopenid;
            }
            if (!empty($qqopenid)) {
                $update_data['qqopenid'] = $qqopenid;
            }
            if (!empty($zfbopenid)) {
                $update_data['zfbopenid'] = $zfbopenid;
            }
            if (!empty($xcxopenid)) {
                $update_data['xcxopenid'] = $xcxopenid;
            }
            if (!empty($update_data)) {
                $update_data['password'] = md5($pwd);
                $m_userhome->where($map)->update($update_data);
                $this->success('请求成功', '', '200');
            } else {
                $this->error("账号已经存在");
            }
        }

        #验证验证码
        $this->if_code();

        #查询是否有上级
        $p_map['phone'] = $phone;
        $p_data = $m_userphone->field("userhome_id")->where($p_map)->find();
        if (!empty($p_data)) {
            $add_data['pid'] = $p_data['userhome_id'];
        }
        //开启事务
        Db::startTrans();
        #创建用户
        $add_data['nickname'] = $nickname ? $nickname : mb_substr($phone, 0, 3) . '*****' . mb_substr($phone, 8, 3);
        $add_data['phone'] = $phone;
        $add_data['avatar'] = $avatar ? $avatar : "/uploads/moren/moren.jpg";
        if ($pwd) {
            $add_data['password'] = md5($pwd);
        } else {
            $add_data['password'] = md5("liuliuliu123456");
        }
        $add_data['is_renzheng'] = 1;
        $add_data['createtime'] = time();
        $add_data['token'] = md5(time() . rand(1, 10000));
        $add_data['wxopenid'] = $wxopenid;
        $add_data['qqopenid'] = $qqopenid;
        $add_data['zfbopenid'] = $zfbopenid;
        $add_data['xcxopenid'] = $xcxopenid;
        $teamUserPhone = null;
        $result = $m_userhome->insertGetId($add_data);
        $inviteUserId = null;
        $teamUserId = null;
        if (isset($inviteCode) && !empty($inviteCode) && $inviteCode) {
            $inviteUser = $m_userhome->where('inviteCode', $inviteCode)->find();
            if ($inviteUser) {
                $inviteUserId = $inviteUser['id'];
                $add_data['inviteUserId'] = $inviteUserId;
                $teamUserId = $this->setUserInvite($result, $inviteUserId);
            }
        }
        $this->setUserInviteNum($result, $inviteUserId);

        #创建邀请码
        $newInviteCode = date('YmdHis') . rand(0, 9) . rand(0, 9);
        $yq_image = $this->create_image($newInviteCode);
        $yq_map['id'] = $result;
        $yq_data['invite_image'] = $yq_image;
        $yq_data['inviteCode'] = $newInviteCode;
        $yq_data['inviteUserId'] = $inviteUserId;
        $yq_data['teamUserId'] = $teamUserId;
        $m_userhome->where($yq_map)->update($yq_data);
        #返回用户信息
        $user_data['id'] = $result;
        $user_data['avatar'] = path($add_data['avatar']);
        $user_data['nickname'] = $add_data['nickname'];
        $user_data['phone'] = $add_data['phone'];
        $user_data['token'] = $add_data['token'];

        require_once "./huanxin/Easemob.class.php";
        $e = new \Easemob();
        #注册环信
        $e->createUser($result, "123456", $add_data['nickname']);
        #设置属性  头像、昵称
        $e->editUser($result, $add_data['nickname'], $user_data['avatar']);

        if (!empty($p_data)) {
            #查询上级是否有群,有则拉入营销群
            $group_map['userhome_id'] = $p_data['userhome_id'];
            $group_map['type'] = '1';
            $group_data = $m_usergroup->where($group_map)->find();

            $result_u = $e->addGroupMember($group_data['groupnumber'], $result);

            $jinyan_data[] = $result;
            $e->addGroupJinyan($group_data['groupnumber'], $jinyan_data);
        }
        Db::commit();
        $this->success('请求成功', '', '200');
    }


    /**
     * 在环信即时通讯系统注册为IM用户
     * @param $username 用户名
     * @param $password 登录密码
     * @param $nickname 昵称
     */
    public function registerImUser($username, $password, $nickname)
    {
        require_once "./huanxin/Easemob.class.php";
        $e = new \Easemob();
        //传入用户名和登录密码参数注册为IM用户
        $result_u = $e->createUser($username, $password, $nickname);
        return $result_u;
    }


    /*
    * 忘记密码
    */
    public function forgot_password()
    {
        $m_userhome = Db::name("userhome");

        $request = Request::instance();
        $phone = $request->param("phone");
        $pwd = $request->param("pwd");

        if (empty($pwd)) {
            $this->error("密码不能为空", '', '201');
        }

        #判断是否注册
        $map['phone'] = $phone;
        $data = $m_userhome->where($map)->find();
        if (empty($data)) {
            $this->error("账号不存在");
        }

        #验证验证码
        $this->if_code();

        $user_map['id'] = $data['id'];
        $user_update['password'] = md5($pwd);
        $m_userhome->where($user_map)->update($user_update);

        $this->success("成功", '', '200');
    }

//    /*
//    * 邀请
//    */
//    public function invitation(){
//        $m_userphone = Db::name("userphone");
//        $m_userhome = Db::name("userhome");
//
//        $request = Request::instance();
//        $pid = $request->param("pid");
//        $phone = $request->param("phone");
//
//        #验证验证码
//        $this->if_code();
//
//        $user_map['phone'] = $phone;
//        $user_data = $m_userhome->where($user_map)->find();
//        if(!empty($user_data)){
//            $this->error("手机号已存在");
//        }
//        $inviteCode = $pid;
//        if(isset($inviteCode) && !empty($inviteCode) && $inviteCode){
//            $this->setUserInvite($phone,$inviteCode);
//        }
//        $this->setUserInviteNum($phone,$inviteCode);
//        $data['userhome_id'] = $pid;
//        $data['phone'] = $phone;
//        $if_data = $m_userphone->where($data)->find();
//        if(empty($if_data)){
//            $data['createtime'] = time();
//            $m_userphone->insertGetId($data);
//        }
//        $this->success("成功");
//    }

    public function setUserInviteNum($userId, $inviteUserId)
    {
        $m_user_invite_num = Db::name("user_invite_num");
        $user_invite_num = [];
        $user_invite_num['userId'] = $userId;
        $user_invite_num['inviteUserId'] = $inviteUserId;
        $m_user_invite_num->where('userId', $userId)->delete();
        $m_user_invite_num->insert($user_invite_num);
    }

    public function setUserInvite($userId, $inviteUserId)
    {
        $teamUserId = null;
        $m_userhome = Db::name("userhome");
        $m_userrelation = Db::name("user_relation");
        $m_user_invite_num = Db::name("user_invite_num");
        $m_user_team = Db::name("user_team");
        $inviteUser = $m_userhome->where(['id' => $inviteUserId])->find();
        if ($inviteUser) {
            //如果存在上级
            $userRelation['userId'] = $userId;
            $userRelation['inviteUserId'] = $inviteUser['id'];
            $userRelation['relationList'] = ";" . $inviteUser['id'] . ";";
            $userRelation['createTime'] = date("Y-m-d H:i:s");
            $inviteUserRelation = $m_userrelation->where(['userId' => $inviteUser['id']])->find();
            if ($inviteUserRelation) {
                //如果上级有收益链
                if (isset($inviteUserRelation['relationList']) && !empty($inviteUserRelation['relationList']) && $inviteUserRelation['relationList']) {
                    $userRelation['relationList'] = ";" . $inviteUser['id'] . $inviteUserRelation['relationList'];
                }
            }
            $m_userrelation->where(['userId' => $userId])->delete();
            $m_userrelation->insert($userRelation);
            //准备用户团队关系
            $inviteUserTeam = $m_user_team->where(['userId' => $inviteUser['id']])->where('status', 1)->find();
            if ($inviteUserTeam) {
                //如果上级有收益链
                $userTeam = [];
                $userTeam['userId'] = $userId;
                $userTeam['inviteUserId'] = $inviteUser['id'];
                $userTeam['teamUserId'] = $inviteUser['id'];
                $userTeam['createTime'] = date("Y-m-d H:i:s");
                if (isset($inviteUserTeam['teamUserId']) && !empty($inviteUserTeam['teamUserId']) && $inviteUserTeam['teamUserId']) {
                    $userTeam['teamUserId'] = $inviteUserTeam['teamUserId'];
                }
                $m_user_team->where(['userId' => $userId])->update(['status' => 0, 'updateTime' => date("Y-m-d H:i:s")]);
                $teamUserId = $userTeam['teamUserId'];
                $m_user_team->insert($userTeam);
            }
            $user_invite_num = $m_user_invite_num->where('userId', $inviteUserId)->find();
            if (!$user_invite_num) {
                $user_invite_num = [];
                $user_invite_num['userId'] = $inviteUserId;
                $user_invite_num['inviteUserNum'] = 1;
                $m_user_invite_num->insert($user_invite_num);
            } else {
                $m_user_invite_num->where('userId', $inviteUserId)->update(['inviteUserNum' => $user_invite_num['inviteUserNum'] + 1]);
            }
            if (isset($user_invite_num['inviteUserId']) && !empty($user_invite_num['inviteUserId'])) {
                $oldInviteUserId = $user_invite_num['inviteUserId'];
                $user_invite_num = $m_user_invite_num->where('userId', $oldInviteUserId)->find();
                if (!$user_invite_num) {
                    $user_invite_num = [];
                    $user_invite_num['userId'] = $oldInviteUserId;
                    $user_invite_num['inviteUserNum'] = 1;
                    $user_invite_num['indirectInviteUserNum'] = 1;
                    $m_user_invite_num->insert($user_invite_num);
                } else {
                    $m_user_invite_num->where('userId', $oldInviteUserId)->update(['indirectInviteUserNum' => $user_invite_num['indirectInviteUserNum'] + 1]);
                }
            }
        }
        return $teamUserId;
    }

    /*
    * 上传
    */
    public function shanchuan()
    {
        $files = $this->request->file('files'); //licencelimages 证件上传

        if ($files) {
            $image = $this->oneupload($files);  //用户上传word文件
        } else {
            $this->error("上传失败，请重新上传");
        }
        $this->success("成功", $image);
    }


    public function oneupload($file)
    {
        $new_file1 = '/uploads/' . date("Ymd", time());
        if (!file_exists($new_file1)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file1, 0700);
        }
        if ($file) {
            $info = $file->move('/uploads/');
            if ($info) {
                $result = '/uploads/' . date("Ymd", time()) . '/' . $info->getFilename();
                $this->oss_file($result);
                return $result;
            } else {
                return $file->getError();
            }
        }
    }

    /**
     * InfoStr APP登录需要的的infostr
     * @return String
     */
    public function get_infostr()
    {
        $infoStr = http_build_query([
            'apiname' => 'com.alipay.account.auth',
            'method' => 'alipay.open.auth.sdk.code.get',
            'app_id' => '2021002182617884',//应用id
            'app_name' => 'mc',
            'biz_type' => 'openservice',
            'pid' => '2088241453829747', //商户id,2088开头的 2088831734781215
            'product_id' => 'APP_FAST_LOGIN',
            'scope' => 'kuaijie',
            'target_id' => time(), //商户标识该次用户授权请求的ID，该值在商户端应保持唯一
            'auth_type' => 'AUTHACCOUNT', // AUTHACCOUNT代表授权；LOGIN代表登录
            'sign_type' => 'RSA2',
        ]);
        $infoStr .= '&sign=' . $this->enRSA2($infoStr);
        $this->success('成功', $infoStr, 200);
    }

    /**
     * enRSA2 RSA加密
     * @param String $data
     * @return String
     */
    private function enRSA2($data)
    {
        $private_key = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCykKr+nuwgwviNEAEdUD7BomIPSFn25XM7a2dzaBLLwVZbC1AZ6PsCGjDyIeTi/L8WECZ/m251cc05ntBfIlnIawwX8DsnZB7/O8usL21rjVyatUFTzW+gz0v7/H0OAj/503g8jBczWFbnxONmstaAo7VCLQ163qfkEYB3a3uo/jMbm0TmvJ50QKh75uvazlptXBxmqUlEhj1qicpdyhz99cbS/2bn4Ci+5CcY9UIBIlXn/iGCWQ/CvxpXbtKGKUQu9UmdROCcM5D5SmEiSWTBn5Pt5tJzTWqK3h+wxlaArdAvf/YOJUin7GoXgjSguRJ28NXftsmt0vT9Johe+cAxAgMBAAECggEATHpjkjw0u+9ljt0s7QYiasKGpy8AwRsS2H8uxqHrcvMybjoRK5e6cfMPxZS4uHMx0FxIcNz8WTbNhAE+E5DdzVXzzwjn/P4HvJ86o1uIzMi1wdkhyqexSLmgPKOuV+KkzfZBiAUkJqyORCPylVjBQEVda6NqI5bbZ3YLhJo3U3Ab4uBwT8YG8SzETFGHbG8Vqvb4rkFuMUSWm2aczD2JVRYuPoTmjsSezp9x9s6f+wsIqZC/5PmEMG0xfH9fUEXs+OHBVVu58JCJMwo4EwewBN8fWQTGLPJIZiUsLqtWCUHJ7/wSNU/Mp8RtDzaXKFfiuw8Mrc4J2dldUOOlXqS6AQKBgQDu7LaupzOsD3VizUIsxRoG/iIIIktARJJgoRxo+HU0vJ31tQbMntgqR5/VMp4tXa5tCSUZYgYSL7C1bqfHXouHDGj4/OZ+2cGqpYnGGfgNmlgoVi5hb4ncG72ggOYkDwsgv8mCFlyTvDykTb1M5z+upm2uxrIdVK55RRf88V2RIQKBgQC/U6LPGksYUtRcZCQGEa18FWT3aHlRun5m9fEdCjdMGXkhbxPMiFDg/JFtaeVzo7CUxBgMpLPpTOO/gT6FtWPsJvusP67W03yQR7ysdZKtrGPBXARwmQPHahGsV+2BoXk2kObVuc1EaA0oZFOLaJp1sOKEkJIf1zPU1PgBfSZ9EQKBgQCr0buGWmPEhtFqHiZKv+v5v2SF6POo4idKKlKeAp93L3WBL5AWMt1Nenis/1vVUBuR+hOd72piRb2UnGE39PvuQLR06ppv+vVVXPp5Zk+GqMphJ6jvFSFVEvYJqOjYYaElCgdF8ALfk20g028hEOQxGyqhl+6bPTzDpTadBo69QQKBgQCSssQg2948djYR6U6dwKwuehECin6LJd2JgIYxaAXiOZ3g/tRFfTfWapHvPMUMF7RrPLfb6eVwut3dlnGj/+LvzSwndGTQnzPhRL/r0/J1a7rJJY7Z7tkw66lFZd3cCT1xk0ULFv3Gt6lvEQ3l1HyqRMhKMLd55n39cJYAPj9moQKBgBuuK0vSf+9BhqK8/msXlPAYEHv/LFFH1ufvYKu6uPZuGWYWJsrFc+l/xhr1tmebPnENhSb5cZHRdwnq09K0HAGKV1NvNmQdrnvFAOANdb22Ovu8Q4Bbp1NVp28IjaDOR6CAXOcCM1HUJVMuqHHQ3123ISp10W2JNE67ss49lnB0';
        $str = chunk_split(trim($private_key), 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n$str-----END RSA PRIVATE KEY-----\n";
        // $key = file_get_contents(storage_path('rsa_private_key.pem')); 为文件时这样引入
        $signature = '';
        $signature = openssl_sign($data, $signature, $key, OPENSSL_ALGO_SHA256) ? base64_encode($signature) : NULL;
        return $signature;
    }


    //支付宝获取用户信息
    public function alipay_getuserinfo()
    {
        $m_userhome = Db::name("userhome");

        $code = $this->request->param('code');
        if (empty($code)) {
            $this->error('缺少参数code', '', 201);
        }
        //phpinfo();die; 5.5.9
        include "./alipay/aop/AopClient.php";
        include "./alipay/aop/AopCertClient.php";
        include "./alipay/aop/request/AlipayUserInfoShareRequest.php";
        include "./alipay/aop/request/AlipaySystemOauthTokenRequest.php";
        $c = new \AopCertClient();
        $appCertPath = "./zhengshu/appCertPublicKey_2021002182617884.crt";//应用公钥
        $alipayCertPath = "./zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
        $rootCertPath = "./zhengshu/alipayRootCert.crt";//支付宝根证书

        $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $c->appId = "2021002182617884";
        //商户私钥
        $c->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCykKr+nuwgwviNEAEdUD7BomIPSFn25XM7a2dzaBLLwVZbC1AZ6PsCGjDyIeTi/L8WECZ/m251cc05ntBfIlnIawwX8DsnZB7/O8usL21rjVyatUFTzW+gz0v7/H0OAj/503g8jBczWFbnxONmstaAo7VCLQ163qfkEYB3a3uo/jMbm0TmvJ50QKh75uvazlptXBxmqUlEhj1qicpdyhz99cbS/2bn4Ci+5CcY9UIBIlXn/iGCWQ/CvxpXbtKGKUQu9UmdROCcM5D5SmEiSWTBn5Pt5tJzTWqK3h+wxlaArdAvf/YOJUin7GoXgjSguRJ28NXftsmt0vT9Johe+cAxAgMBAAECggEATHpjkjw0u+9ljt0s7QYiasKGpy8AwRsS2H8uxqHrcvMybjoRK5e6cfMPxZS4uHMx0FxIcNz8WTbNhAE+E5DdzVXzzwjn/P4HvJ86o1uIzMi1wdkhyqexSLmgPKOuV+KkzfZBiAUkJqyORCPylVjBQEVda6NqI5bbZ3YLhJo3U3Ab4uBwT8YG8SzETFGHbG8Vqvb4rkFuMUSWm2aczD2JVRYuPoTmjsSezp9x9s6f+wsIqZC/5PmEMG0xfH9fUEXs+OHBVVu58JCJMwo4EwewBN8fWQTGLPJIZiUsLqtWCUHJ7/wSNU/Mp8RtDzaXKFfiuw8Mrc4J2dldUOOlXqS6AQKBgQDu7LaupzOsD3VizUIsxRoG/iIIIktARJJgoRxo+HU0vJ31tQbMntgqR5/VMp4tXa5tCSUZYgYSL7C1bqfHXouHDGj4/OZ+2cGqpYnGGfgNmlgoVi5hb4ncG72ggOYkDwsgv8mCFlyTvDykTb1M5z+upm2uxrIdVK55RRf88V2RIQKBgQC/U6LPGksYUtRcZCQGEa18FWT3aHlRun5m9fEdCjdMGXkhbxPMiFDg/JFtaeVzo7CUxBgMpLPpTOO/gT6FtWPsJvusP67W03yQR7ysdZKtrGPBXARwmQPHahGsV+2BoXk2kObVuc1EaA0oZFOLaJp1sOKEkJIf1zPU1PgBfSZ9EQKBgQCr0buGWmPEhtFqHiZKv+v5v2SF6POo4idKKlKeAp93L3WBL5AWMt1Nenis/1vVUBuR+hOd72piRb2UnGE39PvuQLR06ppv+vVVXPp5Zk+GqMphJ6jvFSFVEvYJqOjYYaElCgdF8ALfk20g028hEOQxGyqhl+6bPTzDpTadBo69QQKBgQCSssQg2948djYR6U6dwKwuehECin6LJd2JgIYxaAXiOZ3g/tRFfTfWapHvPMUMF7RrPLfb6eVwut3dlnGj/+LvzSwndGTQnzPhRL/r0/J1a7rJJY7Z7tkw66lFZd3cCT1xk0ULFv3Gt6lvEQ3l1HyqRMhKMLd55n39cJYAPj9moQKBgBuuK0vSf+9BhqK8/msXlPAYEHv/LFFH1ufvYKu6uPZuGWYWJsrFc+l/xhr1tmebPnENhSb5cZHRdwnq09K0HAGKV1NvNmQdrnvFAOANdb22Ovu8Q4Bbp1NVp28IjaDOR6CAXOcCM1HUJVMuqHHQ3123ISp10W2JNE67ss49lnB0';
        $c->format = "json";
        $c->charset = "GBK";
        $c->signType = "RSA2";

        //调用getPublicKey从支付宝公钥证书中提取公钥
        $c->alipayrsaPublicKey = $c->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $c->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $c->appCertSN = $c->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $c->alipayRootCertSN = $c->getRootCertSN($rootCertPath);

        $request2 = new \AlipaySystemOauthTokenRequest();
        $request2->setGrantType("authorization_code");
        $request2->setCode($code);//"c40524b8859d4334bfb92da8627bUX21"
        $result = $c->execute($request2);
        // dump($result);die;

        // dump($result->error_response->sub_msg);die;
        if (isset($result->error_response->sub_msg)) {
            $this->error($result->error_response->sub_msg, '', 201);
        }

        $responseNode = str_replace(".", "_", $request2->getApiMethodName()) . "_response";
        //dump($responseNode);die;
        $access_token = $result->$responseNode->access_token;
        if (!$access_token) {
            //echo "获取access_token失败";die;
            $this->error('获取access_token失败', '', 201);
        }
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：【alipay.user.info.share】接口进行调用
        $request = new \AlipayUserInfoShareRequest();
        //授权类接口执行API调用时需要带上accessToken
        $response = $c->execute($request, $access_token); //这里传入获取的access_token
        // dump($response);die;
        $responseNodeName = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        //用户信息
        $codes = $response->$responseNodeName->code;
        $uuid = $response->$responseNodeName->user_id;
        if ($codes == '10000') {
            $user_data = $m_userhome->field("id,avatar,nickname,token,phone,zfbopenid")->where("zfbopenid", $uuid)->find();
            if (empty($user_data)) {
                if (isset($response->$responseNodeName->nick_name)) {
                    $nnk = $response->$responseNodeName->nick_name;
                } else {
                    $nnk = '用户_' . substr(time(), -5);
                }
                $user_data = array(
                    'zfbopenid' => $uuid,
                    'nickname' => $nnk,
                    'avatar' => $response->$responseNodeName->avatar,
                    'token' => '',
                    'id' => '',
                    'phone' => '',
                );
                // $m_userhome->insertGetId($user_data);


                $status = 0;
            } else {
                #用户存在，登录，处理token
                $s_map['id'] = $user_data['id'];
                $s_data['token'] = md5(time() . rand(100, 999));
                $m_userhome->where($s_map)->update($s_data);

                $user_data['avatar'] = $this->image_url($user_data['avatar']);
                $user_data['token'] = $s_data['token'];
                // $user_data['zfbopenid'] = $uuid;

                $status = Db::name("userstore")->where("userhome_id = {$user_data['id']}")->value("status");
                if (!$status) {
                    $status = 0;
                }
            }

            $user_data['status'] = $status;

            $this->success('成功', $user_data, 200);
        } else {
            $this->error('失败', '', 201);
        }
    }


    /*
    * 帮助中心
    */
    public function help_center()
    {
        $m_helpcenter = Db::name("helpcenter");

        $list = $m_helpcenter->field("name,content")->select();

        $this->success('成功', $list, 200);
    }


    public function agreement()
    {
        $m_yinsi_xieyi = Db::name("yinsi_xieyi");

        $request = Request::instance();
        $id = $request->param("id");

        $map['id'] = $id;
        $content = $m_yinsi_xieyi->where($map)->value("content");
        if (empty($content)) {
            $content = '';
        }
        $this->success('成功', $content, 200);
    }

    /*
    * 关于我们
    */
    public function about()
    {
        $m_about = Db::name("about");

        $data = $m_about->find();
        $this->success('成功', $data, 200);
    }

    /*
    * 安卓版本号控制
    */
    public function appleand()
    {
        $m_appleand = Db::name("appleand");
        $data = $m_appleand->field("version_number,file,force")->find();
        $data['file'] = path($data['file']);

        $this->success("成功", $data);
    }

    /*
    * 判断版本
    */
    public function if_apple()
    {
        $m_apple = Db::name("apple");
        $request = Request::instance();

        $map['version_number'] = $request->param("version_number");
        $if_apple = $m_apple->where($map)->value("timelist");
        if ($if_apple === null) {
            $if_apple = 2;
        }
        $this->success("成功", $if_apple);
    }

    /*
    * 判断版本
    */
    public function customer_service()
    {
        $m_customerservice = Db::name("customerservice");
        $request = Request::instance();

        $data = $m_customerservice->field("phone,email")->find();
        $this->success("成功", $data);
    }










    #######################################公共方法

    /*
    * 图片路径
    */
    public function image_url($pic)
    {
        if (empty($pic)) {
            $pic = "";
        } else {
            $http = substr($pic, 0, 4);
            if ($http != 'http') {
                $pic = "https://oss.xmw1688.com" . $pic;
            }else{
                if(strstr($pic, 'https://oss.yuncangxiaodian.com/')) {
                    $image = substr($pic, 31);
                    $pic = "https://oss.xmw1688.com" . $image;
                }
            }
        }
        return $pic;
    }


    //*用户手机登录/注册  短信发送模块
    public function app_short_message($phone, $code, $shortid = '')
    {
        require_once "./duanxin/api_demo/SmsDemo.php";
        #ini_set('date.timezone', 'Asia/Shanghai');
        $demo = new \SmsDemo();
        $response = $demo->sendSms(
            "{$phone}", // 短信接收者
            "SMS_226825378", // 短信模板编号
            array(  // 短信模板中字段的值
                "code" => "{$code}",
            ),
            "{$shortid}",
            "乡米网"
        );
        $response = (array)$response;

        if ($response['Code'] == "OK") {
            return true;
        } else {
            return false;
        }
    }


    /*
    * OSS  上传
    */
    public function oss_file($file_url)
    {
        if (is_file(__DIR__ . '/../vendor/aliyun-oss-php-sdk-master/autoload.php')) {
            require_once __DIR__ . '/../vendor/aliyun-oss-php-sdk-master/autoload.php';
        }
        if (is_file(__DIR__ . '/../vendor/vendor/aliyun-oss-php-sdk-master/autoload.php')) {
            require_once __DIR__ . '/../vendor/vendor/aliyun-oss-php-sdk-master/autoload.php';
        }

        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        $accessKeyId = "LTAI5t7vA3qfDyvwzzRZxwWB";
        $accessKeySecret = "UjHW2kt7gWZxES8PPjS2xXWtMpWk3v";
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        $endpoint = "oss-cn-beijing.aliyuncs.com";
        // 填写Bucket名称，例如examplebucket。
        $bucket = "upload-file-image-admin";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        $object = substr($file_url, 1);
        // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        $filePath = $file_url;

        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
            unlink($filePath);   #删除本地文件
        } catch (OssException $e) {
            #printf(__FUNCTION__ . ": FAILED\n");
            #printf($e->getMessage() . "\n");
            #return;
            unlink($filePath);   #删除本地文件
            $this->error("上传失败,请重新上传");
        }
        #print(__FUNCTION__ . "OK" . "\n");
    }

    /*
    * 生成群组头像
    */
    public function group_image($imgs)
    {
        foreach ($imgs as $i => $v) {
            $imgs[$i] = $this->image_url($imgs[$i]);
        }
        /*$imgs = array();
        $imgs[0] = 'http://upload-file-image-admin.oss-cn-beijing.aliyuncs.com/uploads/20210927/0d40410936f6aa58752a2ffd0f18f833.png';
        $imgs[1] = 'http://upload-file-image-admin.oss-cn-beijing.aliyuncs.com/uploads/20210927/9e1595372fbf0793cc1da1b18abb91fe.png';
        $imgs[2] = 'http://upload-file-image-admin.oss-cn-beijing.aliyuncs.com/uploads/20210927/49ebc1a177620126eae1475d039e298a.png';
        $imgs[3] = 'http://upload-file-image-admin.oss-cn-beijing.aliyuncs.com/uploads/20210927/de729d8c387b43d1e90a621a0726cb54.png';
        $imgs[4] = 'http://upload-file-image-admin.oss-cn-beijing.aliyuncs.com/uploads/20210927/ebbf938587c20f06ea1e3282af2fd9d2.png';
        $imgs[5] = 'http://upload-file-image-admin.oss-cn-beijing.aliyuncs.com/uploads/20210927/ebbf938587c20f06ea1e3282af2fd9d2.png';
        $imgs[6] = 'http://upload-file-image-admin.oss-cn-beijing.aliyuncs.com/uploads/20210927/ebbf938587c20f06ea1e3282af2fd9d2.png';
        $imgs[7] = 'http://upload-file-image-admin.oss-cn-beijing.aliyuncs.com/uploads/20210927/ebbf938587c20f06ea1e3282af2fd9d2.png';
        $imgs[8] = 'http://upload-file-image-admin.oss-cn-beijing.aliyuncs.com/uploads/20210927/ebbf938587c20f06ea1e3282af2fd9d2.png';*/

        $new_file = './uploads/' . date("Ymd", time());
        if (!file_exists($new_file)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
        }
        $image_file = $new_file . '/' . $this->random_name() . '.jpg';
        $a = $this->getGroupAvatar($imgs, 1, $image_file);
        $image_file = trim($image_file, '.');

        #上传阿里云
        $this->oss_file($image_file);
        $image_file = $this->image_url($image_file);
        return $image_file;
    }

    /*
    * 随机名字
    */
    public function random_name()
    {
        //strtoupper转换成全大写的
        $charid = md5(uniqid(mt_rand(), true));
        $uuid = substr($charid, 0, 8) . substr($charid, 8, 4) . substr($charid, 12, 4) . substr($charid, 16, 4) . substr($charid, 20, 12);
        return $uuid;
    }

    public function create_image($inviteCode)
    {
        include_once('./phpqrcode/phpqrcode.php');
        $root_url = getSystem("root_url");
        $data = $root_url . "yuncanghtml/#/register?uid=" . $inviteCode . "&phone=" . $inviteCode;
        $image_url = "/uploads/inviteimage/$inviteCode.png";
        $filename = $image_url;
        // 纠错级别：L、M、Q、H
        $errorCorrectionLevel = 'L';
        // 点的大小：1到10
        $matrixPointSize = 12;
        \QRcode::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, 1);
        $this->resize_image($filename, $filename, 350, 350);
        #上传到阿里云
        $this->oss_file($image_url);
        return $image_url;
    }


    /**
     * 按照指定的尺寸压缩图片
     * @param $source_path  原图路径
     * @param $target_path  保存路径
     * @param $imgWidth     目标宽度
     * @param $imgHeight    目标高度
     * @return bool|string
     */
    function resize_image($source_path, $fileName, $imgWidth, $imgHeight)
    {
        $source_info = getimagesize($source_path);
        $source_mime = $source_info['mime'];
        switch ($source_mime) {
            case 'image/gif':
                $source_image = imagecreatefromgif($source_path);
                break;
            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($source_path);
                break;
            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;
            default:
                return false;
                break;
        }
        $target_image = imagecreatetruecolor($imgWidth, $imgHeight); //创建一个彩色的底图
        imagecopyresampled($target_image, $source_image, 0, 0, 0, 0, $imgWidth, $imgHeight, $source_info[0], $source_info[1]);
        //保存图片到本地
        /*$dir = '../'.$target_path. '/'. date("Ymd") . '/';
        if (!is_dir($dir)) {
            mkdir($dir, 0777);
        }*/
        #$fileName = $dir.date("YmdHis").uniqid().'.jpg';
        if (!imagejpeg($target_image, '/' . $fileName)) {
            $fileName = '';
        }
        imagedestroy($target_image);
        return $fileName;

    }


    /**
     * 合成图片
     * @param array $pic_list [图片列表数组]
     * @param boolean $is_save [是否保存，true保存，false输出到浏览器]
     * @param string $save_path [保存路径]
     * @return boolean|string
     */
    public function getGroupAvatar($pic_list = array(), $is_save = false, $save_path = '')
    {
        //验证参数
        if (empty($pic_list) || empty($save_path)) {
            return false;
        }
        if ($is_save) {
            //如果需要保存，需要传保存地址
            if (empty($save_path)) {
                return false;
            }
        }
        // 只操作前9个图片
        $pic_list = array_slice($pic_list, 0, 9);
        //设置背景图片宽高
        $bg_w = 150; // 背景图片宽度
        $bg_h = 150; // 背景图片高度
        //新建一个真彩色图像作为背景
        $background = imagecreatetruecolor($bg_w, $bg_h);
        //为真彩色画布创建白灰色背景，再设置为透明
        $color = imagecolorallocate($background, 200, 200, 200);
        imagefill($background, 0, 0, $color);
        imageColorTransparent($background, $color);
        //根据图片个数设置图片位置
        $pic_count = count($pic_list);
        $lineArr = array();//需要换行的位置
        $space_x = 3;
        $space_y = 3;
        $line_x = 0;
        switch ($pic_count) {
            case 1: // 正中间
                $start_x = intval($bg_w / 4); // 开始位置X
                $start_y = intval($bg_h / 4); // 开始位置Y
                $pic_w = intval($bg_w / 2); // 宽度
                $pic_h = intval($bg_h / 2); // 高度
                break;
            case 2: // 中间位置并排
                $start_x = 2;
                $start_y = intval($bg_h / 4) + 3;
                $pic_w = intval($bg_w / 2) - 5;
                $pic_h = intval($bg_h / 2) - 5;
                $space_x = 5;
                break;
            case 3:
                $start_x = 40; // 开始位置X
                $start_y = 5; // 开始位置Y
                $pic_w = intval($bg_w / 2) - 5; // 宽度
                $pic_h = intval($bg_h / 2) - 5; // 高度
                $lineArr = array(2);
                $line_x = 4;
                break;
            case 4:
                $start_x = 4; // 开始位置X
                $start_y = 5; // 开始位置Y
                $pic_w = intval($bg_w / 2) - 5; // 宽度
                $pic_h = intval($bg_h / 2) - 5; // 高度
                $lineArr = array(3);
                $line_x = 4;
                break;
            case 5:
                $start_x = 30; // 开始位置X
                $start_y = 30; // 开始位置Y
                $pic_w = intval($bg_w / 3) - 5; // 宽度
                $pic_h = intval($bg_h / 3) - 5; // 高度
                $lineArr = array(3);
                $line_x = 5;
                break;
            case 6:
                $start_x = 5; // 开始位置X
                $start_y = 30; // 开始位置Y
                $pic_w = intval($bg_w / 3) - 5; // 宽度
                $pic_h = intval($bg_h / 3) - 5; // 高度
                $lineArr = array(4);
                $line_x = 5;
                break;
            case 7:
                $start_x = 53; // 开始位置X
                $start_y = 5; // 开始位置Y
                $pic_w = intval($bg_w / 3) - 5; // 宽度
                $pic_h = intval($bg_h / 3) - 5; // 高度
                $lineArr = array(2, 5);
                $line_x = 5;
                break;
            case 8:
                $start_x = 30; // 开始位置X
                $start_y = 5; // 开始位置Y
                $pic_w = intval($bg_w / 3) - 5; // 宽度
                $pic_h = intval($bg_h / 3) - 5; // 高度
                $lineArr = array(3, 6);
                $line_x = 5;
                break;
            case 9:
                $start_x = 5; // 开始位置X
                $start_y = 5; // 开始位置Y
                $pic_w = intval($bg_w / 3) - 5; // 宽度
                $pic_h = intval($bg_h / 3) - 5; // 高度
                $lineArr = array(4, 7);
                $line_x = 5;
                break;
        }
        foreach ($pic_list as $k => $pic_path) {
            $kk = $k + 1;
            if (in_array($kk, $lineArr)) {
                $start_x = $line_x;
                $start_y = $start_y + $pic_h + $space_y;
            }
            //获取图片文件扩展类型和mime类型，判断是否是正常图片文件
            //非正常图片文件，相应位置空着，跳过处理
            $image_mime_info = @getimagesize($pic_path);
            if ($image_mime_info && !empty($image_mime_info['mime'])) {
                $mime_arr = explode('/', $image_mime_info['mime']);
                if (is_array($mime_arr) && $mime_arr[0] == 'image' && !empty($mime_arr[1])) {
                    switch ($mime_arr[1]) {
                        case 'jpg':
                        case 'jpeg':
                            $imagecreatefromjpeg = 'imagecreatefromjpeg';
                            break;
                        case 'png':
                            $imagecreatefromjpeg = 'imagecreatefrompng';
                            break;
                        case 'gif':
                        default:
                            $imagecreatefromjpeg = 'imagecreatefromstring';
                            $pic_path = file_get_contents($pic_path);
                            break;
                    }
                    //创建一个新图像
                    $resource = $imagecreatefromjpeg($pic_path);
                    //将图像中的一块矩形区域拷贝到另一个背景图像中
                    // $start_x,$start_y 放置在背景中的起始位置
                    // 0,0 裁剪的源头像的起点位置
                    // $pic_w,$pic_h copy后的高度和宽度
                    imagecopyresized($background, $resource, $start_x, $start_y, 0, 0, $pic_w, $pic_h, imagesx($resource), imagesy($resource));
                }
            }
            // 最后两个参数为原始图片宽度和高度，倒数两个参数为copy时的图片宽度和高度
            $start_x = $start_x + $pic_w + $space_x;
        }
        if ($is_save) {
            $dir = pathinfo($save_path, PATHINFO_DIRNAME);
            if (!is_dir($dir)) {
                $file_create_res = mkdir($dir, 0777, true);
                if (!$file_create_res) {
                    return false;//没有创建成功
                }
            }
            $res = imagejpeg($background, $save_path);
            imagedestroy($background);
            if ($res) {
                return true;
            } else {
                return false;
            }
        } else {
            //直接输出
            header("Content-type: image/jpg");
            imagejpeg($background);
            imagedestroy($background);
        }
    }


    /*
    * excel 批量上传
    */
    public function apply_record_excel()
    {
        $m_teacher = Db::name("teacher");

        $request = Request::instance();
        $filename = $request->param("filename") ? $request->param("filename") : '/123.xlsx';

        if (empty($filename)) {
            $this->error("请上传文件");
        }
        $filename = '.' . $filename;

        require "../vendor/PHPExcel/PHPExcel/IOFactory.php";
        //加载excel文件  
        $objPHPExcelReader = \PHPExcel_IOFactory::load($filename);
        $reader = $objPHPExcelReader->getWorksheetIterator();
        $sheet1 = $objPHPExcelReader->getSheet(0);//选择第几个表，如下面图片，默认有三个表

        //循环读取sheet
        Db::startTrans();
        try {
            foreach ($reader as $sheet) {
                //读取表内容  
                $content = $sheet->getRowIterator();
                //逐行处理 
                $echo_data = array();
                foreach ($content as $key => $items) {

                    $rows = $items->getRowIndex();              //行
                    $columns = $items->getCellIterator();       //列

                    if (!empty($row_arr)) {
                        $aaa = $row_arr[0];
                    }

                    $row_arr = array();
                    //确定从哪一行开始读取
                    if ($rows < 2) {
                        continue;
                    }
                    //逐列读取
                    foreach ($columns as $head => $cell) {
                        //获取cell中数据
                        $data = $cell->getValue();
                        $row_arr[] = $data;
                    }
                    if (empty($row_arr[0])) {
                        $row_arr[0] = $aaa;
                    }
                    #将数据添加到数据库
                    $echo_data[] = $row_arr;
                }
            }
            dump($echo_data);
        } catch (Exception $e) {
            Db::rollback();
            $this->error("出现未知错误,请检查数据");
        }

        Db::commit();
        //$this->success("导入成功");
    }

    public function ipZcode()
    {
        $request = Request::instance();
        $ip = $this->get_user_ip();
        //$ip = request()->ip();
        //return var_dump($ip);
        //$ip = $request->param("ip");//
        $district = "北京";
        if ($ip) {
            $city = $this->ip3area($ip);
            if ($city != "Unknown") {
                $city = explode("省", $city);
                if (isset($city[1])) {
                    $city = explode("市", $city[1]);
                    $district = $city[0];
                }
            }
        }
        $district = DB::name('district')->where('district', 'like', "%$district%")->find();
        $this->success('社科赛斯', $district, 200);
    }

    /**
     * 获取用户真实IP
     * @param int $type
     * @param bool $adv
     * @return mixed
     * @Date: 2021/8/14 11:54
     * @Author wzb
     */
    public function get_user_ip($type = 0, $adv = true)
    {
        $type = $type ? 1 : 0;
        static $ip = null;
        if (null !== $ip) {
            return $ip[$type];
        }

        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDE_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDE_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) {
                    unset($arr[$pos]);
                }
                $ip = trim(current($arr));
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['HTTP_X_FORWARDE_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDE_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }
            $ip = trim(current($arr));
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    function ip3area($ip)
    {
        $ch = curl_init();
        $url = 'https://whois.pconline.com.cn/ipJson.jsp?ip=' . $ip;
        //用curl发送接收数据
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //请求为https
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $location = curl_exec($ch);
        curl_close($ch);
        //转码
        $location = mb_convert_encoding($location, 'utf-8', 'GB2312');
        //var_dump($location);
        //截取{}中的字符串
        $location = substr($location, strlen('({') + strpos($location, '({'), (strlen($location) - strpos($location, '})')) * (-1));
        //将截取的字符串$location中的‘，’替换成‘&’   将字符串中的‘：‘替换成‘=’
        $location = str_replace('"', "", str_replace(":", "=", str_replace(",", "&", $location)));
        //php内置函数，将处理成类似于url参数的格式的字符串  转换成数组
        parse_str($location, $ip_location);
        return $ip_location['addr'];
    }


    function ip2area($ip)
    {
        $area = '';
        if ($this->is_ip($ip)) {
            $tmp = explode('.', $ip);
            if ($tmp[0] == 10 || $tmp[0] == 127 || ($tmp[0] == 192 && $tmp[1] == 168) || ($tmp[0] == 172 && ($tmp[1] >= 16 && $tmp[1] <= 31))) {
                $area = 'LAN';
            } elseif ($tmp[0] > 255 || $tmp[1] > 255 || $tmp[2] > 255 || $tmp[3] > 255) {
                $area = 'Unknown';
            } else {
                $root_path = getSystem("root_path");
                $fileUrl = $root_path . "application/common/ip/ip.class.php";//应用公钥
                $ipfile = $root_path . "application/common/ip/ipdata/";
                require_once $fileUrl;
                $do = new \ip($ip);
                $area = $do->area($ipfile);
            }
        }
        return $area ? $area : 'Unknown';
    }

    function is_ip($ip)
    {
        return preg_match("/^([0-9]{1,3}\.){3}[0-9]{1,3}$/", $ip);
    }

}
